'use client'

import { useState, useCallback } from 'react'
import { Upload, X, File, CheckCircle, AlertCircle, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { filesAPI } from '@/lib/api'
import { toast } from 'sonner'

interface FileUploadProps {
  onUploadSuccess?: (files: any[]) => void
  onClose?: () => void
  multiple?: boolean
  maxFiles?: number
  maxSize?: number // MB
}

interface UploadFile {
  file: File
  id: string
  status: 'pending' | 'uploading' | 'success' | 'error'
  progress: number
  error?: string
  result?: any
}

export function FileUpload({ 
  onUploadSuccess, 
  onClose, 
  multiple = true, 
  maxFiles = 5, 
  maxSize = 10 
}: FileUploadProps) {
  const [uploadFiles, setUploadFiles] = useState<UploadFile[]>([])
  const [isDragging, setIsDragging] = useState(false)
  const [isUploading, setIsUploading] = useState(false)

  // 处理文件选择
  const handleFileSelect = useCallback((files: FileList | null) => {
    if (!files) return

    const newFiles: UploadFile[] = Array.from(files).map(file => ({
      file,
      id: Math.random().toString(36).substr(2, 9),
      status: 'pending',
      progress: 0
    }))

    // 验证文件
    const validFiles = newFiles.filter(uploadFile => {
      const file = uploadFile.file
      
      // 检查文件大小
      if (file.size > maxSize * 1024 * 1024) {
        uploadFile.status = 'error'
        uploadFile.error = `文件大小超过 ${maxSize}MB 限制`
        return false
      }

      // 检查文件类型
      const allowedTypes = [
        'image/jpeg', 'image/png', 'image/gif', 'image/webp',
        'application/pdf', 'application/msword', 
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain', 'text/markdown', 'application/json', 'application/xml'
      ]
      
      if (!allowedTypes.includes(file.type)) {
        uploadFile.status = 'error'
        uploadFile.error = '不支持的文件类型'
        return false
      }

      return true
    })

    setUploadFiles(prev => {
      const combined = [...prev, ...validFiles]
      return combined.slice(0, maxFiles)
    })
  }, [maxFiles, maxSize])

  // 处理拖拽
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    handleFileSelect(e.dataTransfer.files)
  }, [handleFileSelect])

  // 上传文件
  const uploadFile = async (uploadFile: UploadFile) => {
    try {
      setUploadFiles(prev => 
        prev.map(f => 
          f.id === uploadFile.id 
            ? { ...f, status: 'uploading', progress: 0 }
            : f
        )
      )

      // 对中文文件名进行编码处理
      const encodedFile = await encodeChineseFileName(uploadFile.file)
      
      const result = await filesAPI.uploadFile(encodedFile)
      
      setUploadFiles(prev => 
        prev.map(f => 
          f.id === uploadFile.id 
            ? { ...f, status: 'success', progress: 100, result }
            : f
        )
      )

      toast.success(`${uploadFile.file.name} 上传成功`)
    } catch (error: any) {
      setUploadFiles(prev => 
        prev.map(f => 
          f.id === uploadFile.id 
            ? { ...f, status: 'error', error: error.message || '上传失败' }
            : f
        )
      )
      toast.error(`${uploadFile.file.name} 上传失败: ${error.message}`)
    }
  }

  // 编码中文文件名
  const encodeChineseFileName = async (file: File): Promise<File> => {
    // 检查文件名是否包含中文字符
    const hasChinese = /[\u4e00-\u9fa5]/.test(file.name)
    
    if (!hasChinese) {
      return file // 不包含中文，直接返回原文件
    }

    try {
      console.log('🔍 开始处理中文文件名:');
      console.log('- 原始文件名:', file.name);
      console.log('- 文件类型:', file.type);
      console.log('- 文件大小:', file.size);
      
      // 🔴 关键：不要编码文件名，直接使用原始中文文件名
      // 编码会导致后端接收时出现乱码问题
      console.log('✅ 保持原始中文文件名，不进行编码');
      
      // 直接返回原文件，让后端处理编码问题
      return file;
      
      // 以下是原来的编码逻辑（已注释）
      /*
      // 对中文文件名进行编码
      const encodedName = encodeURIComponent(file.name)
      console.log('编码后文件名:', encodedName)
      
      // 创建新的 Blob 对象，使用编码后的文件名
      const encodedBlob = new Blob([file], { type: file.type })
      
      // 创建一个新的 File 对象，继承原文件的所有属性
      const encodedFile = Object.assign(encodedBlob, {
        name: encodedName,
        lastModified: file.lastModified,
        size: file.size,
        type: file.type
      }) as File
      
      return encodedFile
      */
    } catch (error) {
      console.error('文件名处理失败:', error)
      return file // 处理失败时返回原文件
    }
  }

  // 开始上传
  const startUpload = async () => {
    const pendingFiles = uploadFiles.filter(f => f.status === 'pending')
    if (pendingFiles.length === 0) return

    setIsUploading(true)
    
    try {
      // 并发上传文件
      await Promise.all(pendingFiles.map(uploadFile))
      
      const successFiles = uploadFiles.filter(f => f.status === 'success')
      if (successFiles.length > 0 && onUploadSuccess) {
        onUploadSuccess(successFiles.map(f => f.result))
      }
      
      toast.success(`成功上传 ${successFiles.length} 个文件`)
    } catch (error) {
      console.error('批量上传失败:', error)
    } finally {
      setIsUploading(false)
    }
  }

  // 🔴 新增：处理弹窗关闭，确保数据刷新
  const handleClose = () => {
    // 如果有文件上传成功，确保调用成功回调
    const successFiles = uploadFiles.filter(f => f.status === 'success')
    if (successFiles.length > 0 && onUploadSuccess) {
      onUploadSuccess(successFiles.map(f => f.result))
    }
    
    // 调用原始的关闭回调
    if (onClose) {
      onClose()
    }
  }

  // 移除文件
  const removeFile = (id: string) => {
    setUploadFiles(prev => prev.filter(f => f.id !== id))
  }

  // 重新上传
  const retryUpload = (id: string) => {
    const uploadFile = uploadFiles.find(f => f.id === id)
    if (uploadFile) {
      uploadFile.status = 'pending'
      uploadFile.progress = 0
      uploadFile.error = undefined
      setUploadFiles([...uploadFiles])
    }
  }

  const pendingCount = uploadFiles.filter(f => f.status === 'pending').length
  const successCount = uploadFiles.filter(f => f.status === 'success').length
  const errorCount = uploadFiles.filter(f => f.status === 'error').length

  return (
    <Card className="w-full max-w-4xl">
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle>文件上传</CardTitle>
          {onClose && (
            <Button variant="ghost" size="icon" onClick={handleClose}>
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 拖拽上传区域 */}
        <div
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            isDragging 
              ? 'border-primary bg-primary/5' 
              : 'border-border hover:border-primary/50'
          }`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
        >
          <Upload className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
          <p className="text-lg font-medium mb-2">
            拖拽文件到此处或点击选择文件
          </p>
          <p className="text-sm text-muted-foreground mb-4">
            支持的文件类型：图片、PDF、文档、文本等
            <br />
            单个文件最大 {maxSize}MB，最多可上传 {maxFiles} 个文件
          </p>
          <Button onClick={() => document.getElementById('file-input')?.click()}>
            选择文件
          </Button>
          <input
            id="file-input"
            type="file"
            multiple={multiple}
            className="hidden"
            onChange={(e) => handleFileSelect(e.target.files)}
            accept="image/*,.pdf,.doc,.docx,.txt,.md,.json,.xml"
          />
        </div>

        {/* 文件列表 */}
        {uploadFiles.length > 0 && (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="font-medium">上传列表</h3>
              <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                <span>待上传: {pendingCount}</span>
                <span>成功: {successCount}</span>
                <span>失败: {errorCount}</span>
              </div>
            </div>
            
            {uploadFiles.map((uploadFile) => (
              <div
                key={uploadFile.id}
                className="flex items-center justify-between p-3 border rounded-lg"
              >
                <div className="flex items-center space-x-3 flex-1">
                  <File className="h-5 w-5 text-muted-foreground" />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium truncate">{uploadFile.file.name}</p>
                    <p className="text-sm text-muted-foreground">
                      {(uploadFile.file.size / 1024 / 1024).toFixed(2)} MB
                    </p>
                  </div>
                </div>

                <div className="flex items-center space-x-2">
                  {/* 状态指示器 */}
                  {uploadFile.status === 'pending' && (
                    <Badge variant="secondary">等待上传</Badge>
                  )}
                  {uploadFile.status === 'uploading' && (
                    <div className="flex items-center space-x-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span className="text-sm">上传中...</span>
                    </div>
                  )}
                  {uploadFile.status === 'success' && (
                    <div className="flex items-center space-x-2 text-green-600">
                      <CheckCircle className="h-4 w-4" />
                      <span className="text-sm">上传成功</span>
                    </div>
                  )}
                  {uploadFile.status === 'error' && (
                    <div className="flex items-center space-x-2 text-red-600">
                      <AlertCircle className="h-4 w-4" />
                      <span className="text-sm">{uploadFile.error}</span>
                    </div>
                  )}

                  {/* 操作按钮 */}
                  {uploadFile.status === 'error' && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => retryUpload(uploadFile.id)}
                    >
                      重试
                    </Button>
                  )}
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => removeFile(uploadFile.id)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 操作按钮 */}
        {uploadFiles.length > 0 && (
          <div className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setUploadFiles([])}
              disabled={isUploading}
            >
              清空列表
            </Button>
            <Button
              onClick={startUpload}
              disabled={isUploading || pendingCount === 0}
            >
              {isUploading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  上传中...
                </>
              ) : (
                `开始上传 (${pendingCount})`
              )}
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  )
}
